<html>
<title>Calculator</title>
<body>

<!-- This is an HTML comment. -->
<h1>Calculator</h1>
Type an mathematical expression in the following box using only +, -, *, or / as operators.
<p>
<form method="GET">
<input type="text" name="expr"><input type="submit" value="Calculate">
</form>
</p>

<h2>Result</h2>
<?php
	function calculate($str) 
	{
		$str = preg_replace('[^0-9\+-\*\/\(\) ]', '', $str);
		$result = $result = create_function("", "return (" . $str . ");" );
		return 0 + $result();
	}
	
	$expr = $_GET["expr"];
	$number_pattern = '[-]*[0-9][0-9]*\.?[0-9]*'; // matches integer or real number
	$operator_pattern = '[+-\/\*]?'; // +, -, /, *
	$pattern_stable = '/^' . $number_pattern . $operator_pattern . '/'; //
	$pattern = '/^' . $number_pattern . '(' . $operator_pattern . $number_pattern . ')*' . '/';
	
	$success = preg_match($pattern, $expr, $matches);
	
	// if there's any regular expression match
	if ($success) 
	{
		$math_expr = $matches[0];
		$division_by_zero = false;
		$div_zero_expr = '/[\/][0]/';
		if (preg_match($div_zero_expr, $math_expr))
		{
			$division_by_zero = true;		
		}

		// have to check division by 0
		// if the expression didn't have to be changed by calculate function
		if ($division_by_zero)
		{
			echo $expr . ' = ';
		}
		else if ($expr == $math_expr) 
		{
			$answer = calculate($math_expr);
			echo $math_expr . ' = ' . $answer;
		}
		else 
		{
			echo 'Invalid input expression ' . $expr . '.'; 
		}
	}
	else 
	{
		echo 'Invalid input expression ' . $expr . '.';
	}
?>

</body>
</html>